package com.web.boot.web.base;

import com.blue.core.dict.HttpMethod;
import com.blue.core.dict.annotation.DictParser;
import com.blue.http.annotation.Http;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.View;
import com.blue.http.message.ViewBuilder;
import com.blue.validation.group.SaveModel;
import com.web.core.async.redis.CacheRefreshSender;
import com.web.core.base.model.Area;
import com.web.core.base.service.AreaService;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller
@Http(url = "/base")
public class AreaController
{
	@Resource
	private AreaService areaService;
	@Resource
	private CacheRefreshSender cacheRefreshSender;
	
	private DictParser dictParser = DictParser.getInstance();
	
	public AreaController()
	{
	}
	
	@Http(url = "/area_list", method = HttpMethod.GET)
	public View listGet(HttpRequest request)
	{
		Area area = request.getQueryObject(Area.class);
		return View.createBuilder().setView("/base/area_list")
				.put("map", dictParser.getStringMap())
				.put("model", area)
				.put("treeList", areaService.listTree(area))
				.build();
	}
	
	@Http(url = "/area_get", method = HttpMethod.GET)
	public View get(HttpRequest request)
	{
		Area area = request.getQueryObject(Area.class);
		if (area.getId() != null)
		{
			area = areaService.get(area.getId());
		}
		ViewBuilder builder = View.createBuilder();
		if (area.getParentId() != null)
		{
			builder.put("parentModel", areaService.get(area.getParentId()));
		}
		return builder.setView("/base/area_get")
				.put("map", dictParser.getStringMap())
				.put("model", area)
				.build();
	}
	
	@Http(url = "/area_save", method = HttpMethod.POST)
	public void save(HttpRequest request)
	{
		Area area = request.getPostObject(Area.class, SaveModel.class);
		areaService.save(area);
		cacheRefreshSender.send(CacheRefreshSender.AREA_CACHE, area.getId());
	}

	@Http(url = "/area_refresh", method = HttpMethod.POST)
	public void refresh(HttpRequest request)
	{
		cacheRefreshSender.send(CacheRefreshSender.AREA_CACHE);
	}
	
}
